<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">

      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleForm(false)"> 新增</a-button>
        <a-dropdown v-if="getSelectRowKeys().length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="i-ant-design:delete-outlined" />
                删除
              </a-menu-item>
              <a-menu-item key="2" @click="batchFrozen(2)">
                <Icon icon="i-ant-design:lock-outlined" />
                冻结
              </a-menu-item>
              <a-menu-item key="3" @click="batchFrozen(1)">
                <Icon icon="i-ant-design:unlock-outlined" />
                解冻
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="i-mdi:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <PasswordModal @register="registerPasswordModal" @success="reload" />
    <AdjustPointForm @register="registerAdjustPoint" @success="reload" />
  </div>
</template>

<script lang="ts" name="system-user" setup>
  //ts语法
  import { ref, computed, unref } from "vue"
  import { BasicTable, TableAction, ActionItem, useTable, BasicColumn } from "/@/components/Table"
  import InputForm from "./Form.vue"
  import PasswordModal from "./PasswordModal.vue"
  import AdjustPointForm from "./AdjustPointForm.vue"
  import { useDrawer } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { columns, searchFormSchema } from "./user.data"
  import { deleteUser, batchDeleteUser, frozenBatch } from "/@/api/member/user.api"
  import { pageMemberUser } from "/@/api/member/user.api.ts"
  import { Icon } from "/@/components/Icon"
  import { useGo } from "/@/hooks/web/usePage"
  // import { usePermission } from '/@/hooks/web/usePermission'
  // const { hasPermission } = usePermission();

  const { createMessage, createConfirm } = useMessage()
  const go = useGo()
  const selectRows = ref([])
  const [registerDrawer, { openDrawer }] = useDrawer()
  const [registerAdjustPoint, { openDrawer: openAdjustPoint }] = useDrawer()

  const [registerPasswordModal, { openModal: openPasswordModal }] = useModal()

  const actionColumn: BasicColumn = {
    width: 150,
    title: "操作",
    dataIndex: "action",
    fixed: "right",
    slot: "tableActions",
    actions: (record) => [
      {
        label: "详情",
        onClick: handleGoDetails.bind(null, record),
      },
      {
        label: "冻结",
        ifShow: record.status === "1",
        color: "error",
        // auth: 'sys:area:updateStatus',
        popConfirm: {
          title: "确定冻结吗?",
          confirm: handleUpdateStatus.bind(null, record.id, "2"),
        },
      },
      {
        label: "启用",
        ifShow: record.status === "2",
        // auth: 'sys:area:updateStatus',
        popConfirm: {
          title: "确定启用吗?",
          confirm: handleUpdateStatus.bind(null, record.id, "1"),
        },
      },
    ],
    dropDownActions: (record: Recordable) => [
      {
        label: "编辑",
        // auth: 'sys:area:update',
        onClick: handleForm.bind(null, true, record),
      },
      {
        label: "删除",
        color: "error",
        ifShow: record.sendStatus != 1,
        // auth: 'sys:area:delete',
        popConfirm: {
          title: "是否确认删除",
          confirm: handleDelete.bind(null, record),
        },
      },
      {
        label: "调整积分",
        // auth: 'sys:area:update',
        onClick: handleAdjustPoint.bind(null, record),
      },
    ],
  }

  const [registerTable, { reload, updateTableDataRecord, rowSelection, getSelectRowKeys }] = useTable({
    title: "会员列表",
    api: pageMemberUser,
    bordered: false,
    columns: columns,
    size: "small",
    formConfig: {
      baseColProps: { lg: 6, md: 12 },
      labelWidth: 90,
      schemas: searchFormSchema,
      showResetButton: false,
    },
    actionColumn,
    showTableSetting: true,
    useSearchForm: true,
    pagination: true,
    canResize: true,
    rowKey: "id",
    beforeFetch: (params) => {
      return Object.assign({ column: "createTime", order: "desc" }, params)
    },
  })

  const handleUpdateStatus = (id, status) => {
    frozenBatch({ ids: id, status }, () => {
      createMessage.success("更新成功")
      reload()
    })
  }

  const handleAdjustPoint = (record) => {
    openAdjustPoint(true, { record, showFooter: true })
  }

  const handleGoDetails = (record) => {
    window.open(`/member/user/detail?id=${record?.id}`, "_blank")
  }

  function handleForm(isUpdate, record?: Recordable) {
    console.time("user-drawer")
    openDrawer(true, {
      record,
      isUpdate,
      showFooter: true,
    })
  }

  async function handleDetail(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
      showFooter: false,
    })
  }

  async function handleDelete(record) {
    if (record.isAdmin) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await deleteUser({ id: record.id }, reload)
  }

  async function batchHandleDelete() {
    let hasAdmin = unref(selectRows).filter((item) => item.isAdmin)
    if (unref(hasAdmin).length > 0) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await batchDeleteUser({ ids: getSelectRowKeys() }, () => {
      // selectedRowKeys.value = []
      reload()
    })
  }

  function handleSuccess({ isUpdate, values }) {
    reload()
    if (isUpdate) {
      updateTableDataRecord(values.id, values)
      createMessage.success("编辑成功")
    } else {
      createMessage.success("新增成功")
    }
  }

  /**
   * 打开修改密码弹窗
   */
  function handleChangePassword(userName, id) {
    openPasswordModal(true, { userName, id })
  }

  function batchFrozen(status) {
    let hasAdmin = unref(selectRows).filter((item) => item.isAdmin)
    if (unref(hasAdmin).length > 0) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    createConfirm({
      iconType: "warning",
      title: "确认操作",
      content: "是否" + (status == 1 ? "解冻" : "冻结") + "选中账号?",
      onOk: async () => {
        await frozenBatch({ ids: unref(getSelectRowKeys()).join(","), status: status }, reload)
      },
    })
  }
</script>

<style scoped></style>
